﻿using LJSheng.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LJSheng.Web
{
    public partial class kmpost : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //如果刷新网页
            if (!IsPostBack)
            {
                using (EFDB db = new EFDB())
                {
                    var b = db.LJSheng.ToList();
                    var ggdb = b.Where(l => l.real_name == "公告").FirstOrDefault();
                    if (ggdb != null && !string.IsNullOrEmpty(ggdb.explain))
                    {
                        gg.InnerHtml = ggdb.explain;
                    }
                    var ptbdb = b.Where(l => l.real_name == "普通").FirstOrDefault();
                    if (ptbdb != null && !string.IsNullOrEmpty(ptbdb.explain))
                    {
                        ptb.InnerHtml = ptbdb.account;
                        ptb.HRef = ptbdb.explain;
                    }
                    var gjbdb = b.Where(l => l.real_name == "高级").FirstOrDefault();
                    if (gjbdb != null && !string.IsNullOrEmpty(gjbdb.explain))
                    {
                        gjb.InnerHtml = gjbdb.account;
                        gjb.HRef = gjbdb.explain;
                    }
                    var sysmdb = b.Where(l => l.real_name == "说明").FirstOrDefault();
                    if (sysmdb != null && !string.IsNullOrEmpty(sysmdb.explain))
                    {
                        sysm.InnerHtml = sysmdb.account;
                        sysm.HRef = sysmdb.explain;
                    }
                }
                //this.Response.Write("<script language=javascript>alert('第一次请求!');</script>");
            }
        }

        protected void hebt_Click(object sender, EventArgs e)
        {
            if (Request["jqm"].ToString().Length > 3 && Request["kami"].ToString().Length > 8 && Request["beizhu"].ToString().Length > 1)
            {
                string km = Request["kami"].ToString().Trim();
                string jqm = Request["jqm"].ToString().Trim();
                using (EFDB db = new EFDB())
                {
                    //查询卡密是否可用
                    var b = db.LOrder.Where(l => l.coupon_number == km && l.pay_status == 2).FirstOrDefault();
                    if (b != null)
                    {
                        //查询机器码位数
                        var s = db.ShopList.Where(l => l.gid == b.buygid).FirstOrDefault();
                        if (s != null &&(s.xfd==0 || jqm.Length == s.xfd))
                        {
                            //判断机器码是否注册过
                            var jqzc = db.LOrder.Where(l =>l.pay_type!=4 && l.remarks.Contains(jqm)).FirstOrDefault();
                            bool bl = false;
                            //string beizhu = jqm + " " + DateTime.Now.ToString("dd.MM.") + " " + Request["beizhu"].ToString().Trim() + " |" + DateTime.Now.AddDays(b.tianshu).ToString("yyyy.MM.dd") + "|";
                            if (jqzc== null)//机器码没注册过
                            {
                                b.remarks = jqm + " " + DateTime.Now.ToString("dd.MM.") + " " + Request["beizhu"].ToString().Trim() + " |" + DateTime.Now.AddDays(b.tianshu).ToString("yyyy.MM.dd") + "|"; ;
                            }
                            else
                            {
                                bl = true;
                                //注册过原来数据增加时间
                                string[] jqxf = jqzc.remarks.Split(' ');
                                DateTime dqsj = DateTime.Parse(jqxf[3].Replace("|", "").Replace(".", "-"));
                                if (dqsj <= DateTime.Now)
                                {
                                    dqsj = DateTime.Now;
                                }
                                jqzc.remarks = jqm + " " + DateTime.Now.ToString("dd.MM.") + " " + Request["beizhu"].ToString().Trim() + " |" + dqsj.AddDays(b.tianshu).ToString("yyyy.MM.dd") + "|";
                                if (db.SaveChanges() != 1)
                                {
                                    LJSheng.Common.LogManager.WriteLog("续费失败", beizhu + "\r\n卡密=" + km + "\r\n机器=" + jqm);
                                }
                                b.remarks = "已续费机器=" + jqm;
                                b.pay_type = 4;//续费
                            }
                            b.pay_status = 1;//已核销
                            b.zhekou = "";
                            b.pay_time = DateTime.Now;
                            if (db.SaveChanges() == 1)
                            {
                                if (bl)
                                {
                                    this.Response.Write("<script language=javascript>alert('续费成功,增加 " + b.tianshu.ToString() + " 天');</script>");
                                }
                                else
                                {
                                    this.Response.Write("<script language=javascript>alert('激活成功,有效期 " + b.tianshu.ToString() + " 天');</script>");
                                }
                            }
                            else
                            {
                                LJSheng.Common.LogManager.WriteLog("激活失败", beizhu + "\r\n卡密=" + km);
                                this.Response.Write("<script language=javascript>alert('激活失败或该卡密和机器码已绑定过,请确认!');</script>");
                            }

                            //string beizhu = Request["jqm"].ToString() + " " + DateTime.Now.Day.ToString() + "." + DateTime.Now.Month.ToString() + ". " + Request["beizhu"].ToString() + " |"+ DateTime.Now.AddDays(b.tianshu).ToString("yyyy.MM.dd") +"|";
                            //string data = "api_folder_key=bb&api_paste_name=qq&api_user_key=66346b8a6cd5c9af6390a1da6154d022&api_dev_key=OSe1R2WAGj3AuN-YuhMYU5FZI5US80hm&api_option=paste&api_paste_code=" + beizhu;
                            //string post = Post("https://pastebin.com/api/api_post.php", data);
                            //if (post.Contains("https://pastebin.com"))
                            //{
                            //}
                            //Response.Write(post);
                        }
                        else
                        {
                            this.Response.Write("<script language=javascript>alert('卡密和机器码对不上,请购买对应的卡密,当前卡类型="+ s.name+"');</script>");
                        }
                    }
                    else
                    {
                        var dd = db.LOrder.Where(l => l.coupon_number == km && l.pay_status == 1).FirstOrDefault();
                        if (dd == null && Request.QueryString["pay"]!="1")
                        {
                            this.Response.Write("<script language=javascript>alert('卡密无效或已激活,请核对!');</script>");
                        }
                        else
                        {
                            //查询位数
                            var s = db.ShopList.Where(l => l.gid == dd.buygid).FirstOrDefault();
                            if (s != null && (s.xfd == 0 || jqm.Length == s.xfd))
                            {
                                if (dd.pay_type == 4)
                                {
                                    string jq = dd.remarks.Split('=')[1];
                                    dd = db.LOrder.Where(l => l.remarks.Contains(jq) && l.pay_status == 1 && l.pay_type != 4).FirstOrDefault();
                                }
                                string[] str = dd.remarks.Split(' ');
                                dd.remarks = jqm + " " + str[1] + " " + Request["beizhu"].ToString().Trim() + " " + str[3];
                                if (db.SaveChanges() == 1)
                                {
                                    this.Response.Write("<script language=javascript>alert('修改机器码成功,新机器码=" + jqm + "');</script>");
                                }
                                else
                                {
                                    LJSheng.Common.LogManager.WriteLog("变更失败", beizhu + "\r\n卡密=" + km + "\r\n机器=" + jqm);
                                    this.Response.Write("<script language=javascript>alert('变更失败,请重试!');</script>");
                                }
                            }
                            else
                            {
                                this.Response.Write("<script language=javascript>alert('当前卡密不能激活此类型机器码,当前卡类型=" + s.name + "');</script>");
                            }
                        }
                    }
                }
            }
            else
            {
                this.Response.Write("<script language=javascript>alert('填写的机器码/备注或卡密位数不符合');</script>");
            }
        }

        private string Post(string url, string PostString)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";  //设置POST请求模式
            //设置参数，POST参数的格式是  参数1=值1&参数2=值2&参数3=值3
            //将参数字符串转换成字节数组。
            byte[] PostData = System.Text.Encoding.UTF8.GetBytes(PostString);
            request.ContentType = "application/x-www-form-urlencoded"; //设置ContntType ，这句很重要，否则无法传递参数
            request.ContentLength = PostData.Length;                 //设置请求内容大小，当然就设置成我们的参数字节数据大小。
            Stream requestStream = request.GetRequestStream();       //获取请求流
            requestStream.Write(PostData, 0, PostData.Length);       //将参数字节数组写入到请求流里
            requestStream.Close();                                   //关闭请求流
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();       //执行请求，获取响应对象
            Stream stream = response.GetResponseStream();                           //获取响应流
            StreamReader sr = new StreamReader(stream);                             //创建流读取对象
            string responseHTML = sr.ReadToEnd();                     //读取响应流                         //
            response.Close();                                         //关闭响应流
            return responseHTML;
        }
    }
}